module.exports = (sequelize, DataTypes) => {
  const Lesson = sequelize.define('Lesson', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: '主键ID'
    },
    categoryId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      field: 'category_id',
      comment: '分类ID'
    },
    title: {
      type: DataTypes.STRING(200),
      allowNull: false,
      comment: '课程标题'
    },
    slug: {
      type: DataTypes.STRING(200),
      allowNull: false,
      unique: true,
      comment: 'URL友好标识'
    },
    content: {
      type: DataTypes.TEXT('long'),
      allowNull: false,
      comment: '课程内容(Markdown格式)'
    },
    excerpt: {
      type: DataTypes.TEXT,
      comment: '课程摘要'
    },
    coverImage: {
      type: DataTypes.STRING(255),
      field: 'cover_image',
      comment: '封面图片URL'
    },
    difficulty: {
      type: DataTypes.ENUM('beginner', 'intermediate', 'advanced'),
      defaultValue: 'beginner',
      comment: '难度等级'
    },
    duration: {
      type: DataTypes.INTEGER,
      comment: '预计学习时长(分钟)'
    },
    sortOrder: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      field: 'sort_order',
      comment: '排序权重'
    },
    isPublished: {
      type: DataTypes.BOOLEAN,
      defaultValue: true,
      field: 'is_published',
      comment: '是否发布'
    },
    isFeatured: {
      type: DataTypes.BOOLEAN,
      defaultValue: false,
      field: 'is_featured',
      comment: '是否推荐'
    },
    viewCount: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      field: 'view_count',
      comment: '浏览次数'
    },
    likeCount: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      field: 'like_count',
      comment: '点赞次数'
    },
    author: {
      type: DataTypes.STRING(100),
      comment: '作者'
    },
    metaKeywords: {
      type: DataTypes.STRING(255),
      field: 'meta_keywords',
      comment: 'SEO关键词'
    },
    metaDescription: {
      type: DataTypes.STRING(255),
      field: 'meta_description',
      comment: 'SEO描述'
    },
    // 虚拟字段：封面图片完整URL
    coverImageUrl: {
      type: DataTypes.VIRTUAL,
      get() {
        const coverImage = this.getDataValue('coverImage');
        if (!coverImage) return null;
        
        // 如果已经是完整URL，直接返回
        if (coverImage.startsWith('http://') || coverImage.startsWith('https://')) {
          return coverImage;
        }
        
        // 如果是相对路径，构建完整URL
        const baseUrl = process.env.BASE_URL || `http://localhost:${process.env.PORT || 3001}`;
        return `${baseUrl}${coverImage}`;
      }
    }
  }, {
    tableName: 'lessons',
    underscored: true,
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    comment: '课程内容表',
    indexes: [
      {
        unique: true,
        fields: ['slug']
      },
      {
        fields: ['category_id']
      },
      {
        fields: ['difficulty']
      },
      {
        fields: ['is_published']
      },
      {
        fields: ['sort_order']
      },
      {
        fields: ['created_at']
      },
      {
        fields: ['category_id', 'is_published', 'sort_order']
      },
      {
        fields: ['difficulty', 'is_published']
      },
      {
        fields: ['is_featured', 'is_published']
      }
    ]
  });

  Lesson.associate = (models) => {
    // 与分类的关联
    Lesson.belongsTo(models.Category, {
      foreignKey: 'categoryId',
      as: 'category'
    });
    
    // 与标签的多对多关联
    Lesson.belongsToMany(models.Tag, {
      through: models.LessonTag,
      foreignKey: 'lessonId',
      otherKey: 'tagId',
      as: 'tags'
    });
    
    // 与代码示例的关联
    Lesson.hasMany(models.CodeExample, {
      foreignKey: 'lessonId',
      as: 'codeExamples',
      onDelete: 'CASCADE'
    });

    // 与用户进度的关联（如果启用用户功能）
    if (models.UserProgress) {
      Lesson.hasMany(models.UserProgress, {
        foreignKey: 'lessonId',
        as: 'userProgress',
        onDelete: 'CASCADE'
      });
    }
  };

  return Lesson;
}; 